import React, {Component, ComponentClass} from 'react';
import Taro from '@tarojs/taro';
import {AtIcon} from 'taro-ui'
import {View, Navigator, Image, Radio, Text} from '@tarojs/components'
import {connect} from 'react-redux'
import {Address, CityLocation as CityLocationType} from '../../utils/server.interface'
import {user} from '../../utils/user.service'
import {http} from "../../utils/http";
import {ADDRESS_LIST, RESOURCE_URL} from "../../constants/api";
import {getHeadTop, vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './index.scss'

type PageStateProps = {
  location: CityLocationType
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  list: Address[]
  fromOrder: boolean
  searchBarTop: number
  limit: number
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Index {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({}))

class Index extends Component {
  state: PageState = {
    loadMoreStatus: 'loading',
    list: [],
    fromOrder: false,
    searchBarTop: 0,
    limit: 20,
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const my = Taro.getCurrentInstance().router.params.my as string | undefined;
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 30) : (headTop.statusBar + headTop.top + 40)
    this.setState({searchBarTop})
    if (!my) {
      this.setState({fromOrder: true})
    }
  }

  async componentDidShow() {
    vcmonitor(this);
    await Taro.setNavigationBarTitle({
      title: '地址管理'
    })
    const id = Taro.getCurrentInstance().router.params.id as string | 0;
    const list = await this.getAdds(this.page, this.state.limit)
    if (list) {
      list.map((item) => {
        item['checked'] = item.id == id;
      })
    }
    this.setState({list})
    this.shareParams = await user.getSellerParams()
  }

  shareParams = ''
  page = 1

  jump(id, e) {
    e.stopPropagation()
    const {list} = this.state
    Taro.navigateTo({
      url: '/other/address/detail?id=' + id + "&listnum=" + list.length
    })
  }

  checkSelf(index, e) {
    const {list} = this.state
    list.map((item, i) => {
      item.checked = i == index;
    })
    this.setState({list}, () => {
      const pages = Taro.getCurrentPages()
      const prevPage = pages[pages.length - 2]
      if (prevPage) {
        if (process.env.TARO_ENV === 'h5') {
          prevPage.data.addobj = list[index]
        } else {
          prevPage.data.add = list[index]
        }
        Taro.navigateBack({
          delta: 1
        })
      }
    })
  }

  async getAdds(page = 1, limit = 20) {
    const addData = await http.carGet<Address[]>(ADDRESS_LIST, {page, limit})
    if (addData.length < limit) {
      this.setState({loadMoreStatus: 'noMore'})
    } else {
      this.setState({loadMoreStatus: 'more'})
    }
    return addData
  }

  async onPullDownRefresh() {
    this.page = 1
    this.setState({loadMoreStatus: 'loading', list: []}, async () => {
      const list = await this.getAdds(this.page)
      this.setState({list}, () => {
        Taro.stopPullDownRefresh()
      })
    })
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.list
      this.page++
      const newData = await this.getAdds(this.page, this.state.limit)
      this.setState({list: [...old, ...newData]})
    }
  }

  render() {
    const {loadMoreStatus, list, fromOrder, searchBarTop} = this.state

    return (
      <View className='address-root'>
        <GzhAuth />
        {list.length == 0 && loadMoreStatus != 'loading' && <View className='listNull'>
          <Image src={`${RESOURCE_URL}/resources/images/addressnull.png`} mode='widthFix' />
          <View className='text'>还没添加可用地址哦,快去添加吧</View>
        </View>}
        {list.length > 0 && <View className='add-list'>
          {list.map((item, index) =>
            <View className='list-item' key={index} onClick={this.checkSelf.bind(this, index)}>
              {fromOrder &&
                <View className='checkbox'><Radio checked={item.checked} color='#fe9f00' value={item.id} /></View>}
              <View className='jumpbox'>
                <View className='add-box'>
                  <View className='add-bottom'>{!!item.default && <Text className='default'>默认</Text>}<Text
                    className='address-style'
                  >{item.address}</Text></View>
                  <View className='add-address'>{item.add.replace(/,/g, "")}</View>
                  <View className='add-top'>
                    <Text
                      className='user-name'
                    >{item.name}</Text>{item.phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2")}
                  </View>
                </View>
                <View className='add-edit' onClick={this.jump.bind(this, item.id)}><AtIcon prefixClass='car'
                  value='iconbianji'
                  size='16px'
                  customStyle='font-size: 16px'
                  color='#000'
                /></View>
              </View>
            </View>
          )}
        </View>}
        <View className='bottom-bar'>
          {process.env.TARO_ENV === 'weapp' &&
            <Navigator className='import-add' url='/other/address/detail?wx=true' hoverClass='none'><AtIcon
              className='icon' prefixClass='xxhz' value='weixin1' size='20px' color='#08bb07'
            />微信导入</Navigator>}
          <Navigator className={`address-add ${process.env.TARO_ENV}`} url='/other/address/detail'
            hoverClass='none'
          >新增收货地址</Navigator>
        </View>
      </View>
    );
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
